#include <bits/stdc++.h>
#include <pthread.h>//linux 使用线程，需要 -lpthread
#include <unistd.h>
#include <sys/types.h>
#include <unistd.h>
using namespace std;

// --------------------------------------
//线程创建
//Thread ID如果用16进制打印，我们能够发现，其和一个地址很像
//pthread_create()函数中第三个参数，是启动线程后第一个要执行的函数
//其实其和我们进程的main函数类似，也是线程的main函数，也就是说，那个函数只要结束，线程就结束了
//所以结束线程的一种方案其实就是函数返回
using func_t  = std::function<void()>;

class ThreadData{
    public:
    ThreadData(const std::string &name,const uint64_t create_time,func_t func)
    :m_create_time(create_time)
    ,m_threadname(name)
    ,m_func(func)
    {

    }
    std::string m_threadname;
    uint64_t m_create_time;
    func_t m_func;
};

void *ThreadRoutine(void* arg)
{
    ThreadData* td = static_cast<ThreadData*>(arg);
    while(1)
    {
        std::cout<<"thread name::"<<td->m_threadname<<"\ncreate time::"<<td->m_create_time<<"\n";
        td->m_func();
        sleep(1);
    }
}

void print()
{
    std::cout<<"I am a thread task\n";
}


struct threadManage{
    pthread_t m_tid;
    ThreadData * m_td;
    threadManage(pthread_t tid,ThreadData* td)
    :m_tid(tid)
    ,m_td(td)
    {

    }
};
int main()
{
    std::vector<threadManage> t_array ;
    for(int i = 0;i<10;i++)
    {
        char threadname[66];
        sprintf(threadname,"Thread %d",i);
        pthread_t tid;
        ThreadData *td= new ThreadData(threadname,static_cast<uint64_t>(time(nullptr)),print);
        pthread_create(&tid,nullptr,ThreadRoutine,td);
        t_array.push_back(threadManage(tid,td));
    }

    for(auto t:t_array)
    {
        std::cout<<"###########################\n";
        std::cout<<"thread ID:"<<std::hex<<t.m_tid;//十六进制打印线程ID
        std::cout<<"###########################\n";
    }
    {
        sleep(5);
        std::cout<<"_---------------------------------\n";
        std::cout<< getpid()<<std::endl;
        std::cout<<"_---------------------------------\n";

    }
    return 0;
}